package cn.linran.service.impl;

import cn.linran.domain.MovieTicket;
import cn.linran.domain.User;
import cn.linran.feign.MovieFeignClient;
import cn.linran.mapper.UserMapper;
import cn.linran.result.JSONResult;
import cn.linran.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-08-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private MovieFeignClient movieFeignClient;

    /**
     * 看电影
     *
     * @param movieId 电影标识符
     * @return {@link JSONResult}
     */
    @Override
    public JSONResult watchMovie(Long movieId) {
        return movieFeignClient.watchById(movieId);
    }

    /**
     * 买电影
     *
     * @param movieId 电影标识符
     * @return {@link JSONResult}
     */
    @Override
    public JSONResult buyMovie(Long movieId) {
        // 判断电影服务那边是否成功，如果失败，那么直接返回JSONResult，Data中包含电影票价格
        JSONResult jsonResult = movieFeignClient.buyById(movieId);
        if (!jsonResult.isSuccess()){
            return jsonResult;
        }
        // 如果电影服务那边成功，那么我们直接扣减余额
        User user = selectById(1L);
        BigDecimal bigDecimal = JSONResult.getBigDecimal(jsonResult.getData());//调用方法将obj->bigdecimal
        BigDecimal newDecimal = user.getBalance().subtract(bigDecimal); //减钱
        user.setBalance(newDecimal);
        updateById(user);
        return JSONResult.success();
    }

    /**
     * 新建用户，随机送一张票
     *
     * @param entity 实体
     * @return boolean
     */
    @Override
    public boolean insert(User entity) {
         super.insert(entity);
        // 1.查询所有电影票
        JSONResult jsonResult = movieFeignClient.list();
        // 1.1 Object->list对象集合
        List<MovieTicket> movieTickets = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), MovieTicket.class);
        // 1.2 得到随机数,赠送电影票
        int random = (int)(Math.random() * movieTickets.size());
        MovieTicket movieTicket = movieTickets.get(random);
        movieFeignClient.buyById(movieTicket.getId());//假设买，实际没有通过用户扣款

        return true;
    }
}
